package nickthissen.iracing.parsing;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.util.ArrayList;

import nickthissen.iracing.datamodels.PrivateMessage;
import nickthissen.iracing.datamodels.PrivateMessageItem;
import nickthissen.iracing.datamodels.Result;

/**
 * Created by Nick on 2-6-13.
 */
public class PmParser extends Parser
{
    @Override
    protected Result doParse(String source)
    {
        Result result = new Result();
        PrivateMessage pm = new PrivateMessage();

        log("Start jsoup parsing PM");
        Document doc = Jsoup.parse(source);
        log("Finished jsoup parsing PM");

        Element table = doc.getElementById("forum");
        Element contentDiv = doc.select("div[class=postBody]").first();

        log("table: " + table.outerHtml());
        log("contentDiv: " + contentDiv.outerHtml());

        ArrayList<Element> rows = Parsing.selectChildren(table.select("tbody").first(), "tr");

        // Sender
        Element from = rows.get(1);
        log("from: " + from.outerHtml());

        ArrayList<Element> fromCols = Parsing.selectChildren(from, "td");

        Element fromCol = fromCols.get(1);
        Element link = Parsing.selectChildren(fromCol, "a").get(0);
        String url = link.attr("href");
        log("From url: " + url);

        pm.From = link.text();
        pm.FromCustid = Integer.parseInt(Parsing.getFilenameWithoutExtension(url));

        // Date
        Element date = rows.get(3);
        log("date: " + date.outerHtml());

        ArrayList<Element> dateCols = Parsing.selectChildren(date, "td");
        Element dateCol = dateCols.get(1);
        log("dateCol: " + dateCol.outerHtml());

        pm.Date = dateCol.text();

        // Contents
        log("Start parsing content");

        String html = contentDiv.html();
        Document contentsDoc = Jsoup.parse(html);
        fixVideoTags(contentsDoc);
        contentsDoc = TagSanitizer.sanitize(contentsDoc);
        fixImageTags(contentsDoc);
        fixRelativeUrls(contentsDoc);

        pm.Content = contentsDoc.body().html();

        log("Finished parsing content");

        result.Success = true;
        result.Object = pm;
        return result;
    }

    @Override
    protected String getLogName()
    {
        return "PmParser";
    }

    @Override
    protected Result createDefaultResultObject()
    {
        Result result = new Result();
        PrivateMessage pm = new PrivateMessage();
        pm.From = "<error>";
        pm.FromCustid = 0;
        result.Object = pm;

        result.Message = "Error parsing PM.";
        return result;
    }
}
